package com.qf.business.user.controller;

import com.qf.commons.base.result.R;
import com.qf.commons.base.result.Rs;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.util.UUID;

/**
 * author Ken
 * create_time 2022/11/28
 */
@RestController
@RequestMapping("/user/img")
@Slf4j
public class ImgController {

    /**
     * 读取配置
     */
    @Value("${file.img.uploader}")
    private String uploaderPath;

    @RequestMapping("/uploader")
    public R uploader(MultipartFile file){
        log.debug("[img uploader] 图片上传 - {}", file.getSize());

        File uploadfile = new File(uploaderPath);
        if (!uploadfile.exists()) {
            //如果路径不存在就创建
            uploadfile.mkdirs();
        }

        //生成文件名称
        String fileName = UUID.randomUUID().toString();

        try (
                //上传输入流
                InputStream in = file.getInputStream();
                //输出流
                OutputStream out = new FileOutputStream(new File(uploadfile, fileName));
        ){


            //开始上传
//            byte[] bytes = new byte[1024];
//            int len;
//            while((len = in.read(bytes)) > 0){
//                out.write(bytes, 0, len);
//            }

            //简化写法
            IOUtils.copy(in, out);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        return Rs.create(fileName);
    }

    /**
     * 下载图片
     */
    @RequestMapping("/download")
    public void download(String fileName, HttpServletResponse response){
        try (
                //输入流
                FileChannel inchannel = new FileInputStream(uploaderPath + "/" + fileName).getChannel();
                //输出流
                WritableByteChannel outchannel = Channels.newChannel(response.getOutputStream());
        ){
            //零拷贝
            inchannel.transferTo(0, inchannel.size(), outchannel);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
